/*
 * FlopolAction.java
 *
 * Copyright (C) 2013 UPOU.
 * IS214 - Programming Languages
 * All Rights Reserved.
 *
 * @author Mary Joy Pascual and Simon Zagado
 */

package com.upittic.flopol.action;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.upittc.flopol.constant.FlopolConstant;
import com.upittc.flopol.core.Lexer;
import com.upittc.flopol.core.Parser;
import com.upittc.flopol.core.helper.CoreHelper;
import com.upittc.flopol.gui.FramePanel;
import com.upittc.flopol.gui.beans.MenuBean;
import com.upittc.flopol.gui.beans.SubMenuBean;
import com.upittc.flopol.gui.beans.TimerBean;

public class MenuAction {

	public List<MenuBean> generateMenuList(final FramePanel panel) {

		List<MenuBean> menuList = new ArrayList<MenuBean>();

		// FILE MENU
		MenuBean fileMenu = new MenuBean();
		fileMenu.setMenuName("File");
		fileMenu.setKeyEvent(KeyEvent.VK_F);

		List<SubMenuBean> fileSubMenuList = new ArrayList<SubMenuBean>();
		
		SubMenuBean newSubMenu = new SubMenuBean();
		newSubMenu.setSubMenuName("New File");
		newSubMenu.setImageIcon(new ImageIcon(getClass().getResource(
				"new.png")));
		newSubMenu.setSubEvent(KeyEvent.VK_N);
		newSubMenu.setTooltip("New File");
		newSubMenu.setAction(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				clearAll(panel);
			}
		});
		fileSubMenuList.add(newSubMenu);
		

		SubMenuBean openSubMenu = new SubMenuBean();
		openSubMenu.setSubMenuName("Open File");
		openSubMenu.setImageIcon(new ImageIcon(getClass().getResource(
				"open.png")));
		openSubMenu.setSubEvent(KeyEvent.VK_O);
		openSubMenu.setTooltip("Help Contents");
		openSubMenu.setAction(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser();
				FileNameExtensionFilter filter = new FileNameExtensionFilter(".flop", "flop");
				fileChooser.setFileFilter(filter);
				int returnVal = fileChooser.showOpenDialog(null);
			    if (returnVal == JFileChooser.APPROVE_OPTION) {
			        File file = fileChooser.getSelectedFile();
			        try {
			          clearAll(panel);
			          JTextArea editor = panel.getEditor();
			          editor.read(new FileReader(file.getAbsolutePath() ), null );
			          editor.setTabSize(2);
			          int len = editor.getDocument().getLength();
			          editor.setCaretPosition(len);
			        } catch (IOException ex) {
			          System.out.println("problem accessing file"+file.getAbsolutePath());
			        }
			    } 
			}
		});
		fileSubMenuList.add(openSubMenu);
		
		SubMenuBean saveSubMenu = new SubMenuBean();
		saveSubMenu.setSubMenuName("Save File");
		saveSubMenu.setImageIcon(new ImageIcon(getClass().getResource(
				"save.png")));
		saveSubMenu.setSubEvent(KeyEvent.VK_S);
		saveSubMenu.setTooltip("Save File");
		saveSubMenu.setAction(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				JFileChooser fileChooser = new JFileChooser();
				int returnVal = fileChooser.showSaveDialog(null);
	            if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File fileName = new File(fileChooser.getSelectedFile() + ".flop");
	                try {
	                	BufferedWriter fileOut = new BufferedWriter(new FileWriter(fileName)); 
	                	panel.getEditor().write(fileOut);
	                } catch (Exception e){
	                	 System.out.println("Error");
	                }
	            } 
			}
		});
		fileSubMenuList.add(saveSubMenu);
		
		SubMenuBean exitSubMenu = new SubMenuBean();
		exitSubMenu.setSubMenuName("Exit");
		exitSubMenu.setImageIcon(new ImageIcon(getClass().getResource(
				"exit.png")));
		exitSubMenu.setSubEvent(KeyEvent.VK_E);
		exitSubMenu.setTooltip("Exit Application");
		exitSubMenu.setAction(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				System.exit(0);
			}
		});
		fileSubMenuList.add(exitSubMenu);
		
		fileMenu.setSubMenuList(fileSubMenuList);
		menuList.add(fileMenu);
		

		// RUN MENU
		MenuBean runMenu = new MenuBean();
		runMenu.setMenuName("Run");
		runMenu.setKeyEvent(KeyEvent.VK_R);

		List<SubMenuBean> runSubMenuList = new ArrayList<SubMenuBean>();

		SubMenuBean runSubMenu = new SubMenuBean();
		runSubMenu.setSubMenuName("Run Program");
		runSubMenu
				.setImageIcon(new ImageIcon(getClass().getResource("run.png")));
		runSubMenu.setSubEvent(KeyEvent.VK_P);
		runSubMenu.setTooltip("Run Program");
		runSubMenu.setAction(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				
				TimerBean.startTime();
				panel.getTokenTable().setRowCount(0);
				panel.getConsole().setText("");
				String text = panel.getEditor().getText();
				Lexer lexer = new Lexer(text+FlopolConstant.EOF);
				@SuppressWarnings("unused")
				CoreHelper help = new CoreHelper(panel);
				Parser parser;
				try {
					parser = new Parser(lexer);
					parser.code();
				} catch (Exception e) {
					panel.getConsole().setText(e.getMessage());
					panel.getConsole().setForeground(Color.red);
				} finally {
					panel.getConsole().append(" (Runtime: "+Long.toString(TimerBean.totalTime())+"ms)");
				}
			}
		});

		runSubMenuList.add(runSubMenu);
		runMenu.setSubMenuList(runSubMenuList);
		menuList.add(runMenu);

		// HELP MENU
		MenuBean helpMenu = new MenuBean();
		helpMenu.setMenuName("Help");
		helpMenu.setKeyEvent(KeyEvent.VK_H);

		List<SubMenuBean> helpSubMenuList = new ArrayList<SubMenuBean>();

		SubMenuBean helpSubMenu = new SubMenuBean();
		helpSubMenu.setSubMenuName("Help Contents");
		helpSubMenu.setImageIcon(new ImageIcon(getClass().getResource(
				"help.png")));
		helpSubMenu.setSubEvent(KeyEvent.VK_C);
		helpSubMenu.setTooltip("Help Contents");
		helpSubMenu.setAction(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				JFrame frame = new JFrame();
				JOptionPane.showMessageDialog(frame,
						"GETTING STARTED WITH FLOPOL APPLICATION:\n" +
					    "\n" +
					    "1. There are two ways to put FLOPOL codes into the FLOPOL app:\n" +
					    "    First, you can enter the code directly in the Editor Section.\n" +
					    "    Second, you may upload (from the local drive) a FLOPOL (.flop) file that contains FLOPOL codes with it.\n" +
					    "\n" +
					    "2. To run a FLOPOL program, click the Run Menu and click Run Program.\n" +
					    "\n" +
					    "3. The Console Section will prompt if you have successfully run a program. Else, it will prompt a Syntax or Semantic Error.\n" +
					    "\n",
					    
					    "Help Contents",
				JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(
						"flopol.png")));
			}
		});
		helpSubMenuList.add(helpSubMenu);

		SubMenuBean aboutSubMenu = new SubMenuBean();
		aboutSubMenu.setSubMenuName("About FLOPOL");
		aboutSubMenu.setImageIcon(new ImageIcon(getClass().getResource(
				"about.png")));
		aboutSubMenu.setSubEvent(KeyEvent.VK_A);
		aboutSubMenu.setTooltip("About FLOPOL");
		aboutSubMenu.setAction(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				JFrame frame = new JFrame();
				JOptionPane.showMessageDialog(frame,
					    "Flopol Interpreter for IS214 Students.\n" +
					    "Version: Abaca Release\n" +
					    "Build id: 20131001-0001\n" +
					    "Authors: MJ Pascual and Simon Zagado\n" +
					    "(c) Copyright UPOU contributors and others. 2013.  All rights reserved.\n" +
					    "Visit https://code.google.com/p/is214-interpreter/ \n",
					    "About Flopol",
				JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(
						"flopol.png")));
			}
		});
		helpSubMenuList.add(aboutSubMenu);

		helpMenu.setSubMenuList(helpSubMenuList);
		menuList.add(helpMenu);

		return menuList;

	}
	
	private final void clearAll(FramePanel panel){
		panel.getEditor().setText("");
		panel.getConsole().setText("");
		panel.getSymbolTable().setRowCount(0);
		panel.getTokenTable().setRowCount(0);
	}

}
